package com.faintlight.service.impl;

import com.faintlight.model.Gratitude;
import com.faintlight.model.User;
import com.faintlight.repository.GratitudeRepository;
import com.faintlight.repository.UserRepository;
import com.faintlight.service.GratitudeService;
import com.faintlight.exception.WarmException;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class GratitudeServiceImpl implements GratitudeService {

    private static final Logger logger = LoggerFactory.getLogger(GratitudeServiceImpl.class);
    private final GratitudeRepository gratitudeRepository;
    private final UserRepository userRepository;

    @Override
    @Transactional
    public Gratitude saveGratitude(Gratitude gratitude) {
        logger.info("📌 保存感恩记录: 内容长度={}", gratitude.getContent().length());

        User user = userRepository.findById(gratitude.getUser().getId())
                .orElseThrow(() -> new WarmException("用户不存在"));
        gratitude.setUser(user);

        Gratitude saved = gratitudeRepository.save(gratitude);
        logger.info("✅ 感恩记录保存成功, ID={}", saved.getId());
        return saved;
    }

    @Override
    public List<Gratitude> getUserGratitudes(Long userId) {
        logger.info("🔍 查询用户 {} 的感恩记录", userId);
        List<Gratitude> gratitudes = gratitudeRepository.findByUser_Id(userId);
        logger.info("✅ 查询成功, 共 {} 条记录", gratitudes.size());
        return gratitudes;
    }

    @Override
    @Transactional
    public void deleteGratitude(Long id, Long userId) {
        Gratitude gratitude = gratitudeRepository.findById(id)
                .orElseThrow(() -> new WarmException("未找到感恩记录"));
        if (!gratitude.getUser().getId().equals(userId)) {
            throw new WarmException("没有权限删除这条感恩记录");
        }
        gratitudeRepository.delete(gratitude);
        logger.info("✅ 感恩记录删除成功, ID={}", id);
    }
}